// 事件总线工具
class EventBus {
  constructor() {
    this.events = {};
  }

  // 监听事件
  on(eventName, callback) {
    if (!this.events[eventName]) {
      this.events[eventName] = [];
    }
    this.events[eventName].push(callback);
  }

  // 移除监听
  off(eventName, callback) {
    if (!this.events[eventName]) return;
    if (!callback) {
      delete this.events[eventName];
    } else {
      const index = this.events[eventName].indexOf(callback);
      if (index > -1) {
        this.events[eventName].splice(index, 1);
      }
    }
  }

  // 触发事件
  emit(eventName, data) {
    if (!this.events[eventName]) return;
    this.events[eventName].forEach(callback => {
      try {
        callback(data);
      } catch (error) {
        console.error('事件回调执行错误:', error);
      }
    });
  }

  // 清除所有事件
  clear() {
    this.events = {};
  }
}

// 创建全局事件总线实例
const eventBus = new EventBus();

module.exports = eventBus;
